package com.swan.models;

import com.swan.beans.SeasonBean;
import com.swan.exceptions.CustomerException;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class SeasonDao {

    public boolean addSeason(String seasonName) {
        return DBUtil.doSomething(db ->
                db.updateWithoutGeneratedKey("insert into season (name) values (?)", seasonName) == 1);
    }

    public boolean removeSeason(String seasonName) {
        return DBUtil.doSomething(db ->
                db.updateWithoutGeneratedKey("delete from season where name = ?", seasonName) == 1);
    }

    public List<SeasonBean> list() {
        try (DBUtil db = new DBUtil()) {
            ResultSet rs = db.preparedStatement("select * from season");
            ArrayList<SeasonBean> ret = new ArrayList<>();
            while (rs.next()) {
                ret.add(getSeason(rs));
            }
            return ret;
        } catch (SQLException e) {
            throw new CustomerException(e);
        }
    }

    public SeasonBean getByName(String seasonName) {
        try (DBUtil db = new DBUtil()) {
            ResultSet rs = db.preparedStatement("select * from season where name = ?", seasonName);
            if (rs.next()) {
                return getSeason(rs);
            } else {
                return null;
            }
        } catch (SQLException e) {
            throw new CustomerException(e);
        }
    }

    public SeasonBean getById(int seasonId) {
        try (DBUtil db = new DBUtil()) {
            ResultSet rs = db.preparedStatement("select * from season where id = ?", seasonId);
            if (rs.next()) {
                return getSeason(rs);
            } else {
                return null;
            }
        } catch (SQLException e) {
            throw new CustomerException(e);
        }
    }

    private SeasonBean getSeason(ResultSet rs) throws SQLException {
        return new SeasonBean().setId(rs.getInt("id")).setName(rs.getString("name"));
    }
}
